package com.ruoyi.dataserver.service.impl;

import com.ruoyi.dataserver.model.point.POINT;
import com.ruoyi.dataserver.service.ISearchTableService;
import com.ruoyi.dataserver.service.ITubeAnalyzeService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName
 * @Package com.ruioyi.service.impl
 * @ClassName TopologyAnalyzeServceImpl
 * @Description 管阀逻辑层
 * @Company lab
 * @Author wangw
 * @Date 2020/7/9 0009 11:55
 * @UpdateUser
 * @UpdateDate
 * @UpdateRemark
 * @Version 1.0.0
 */
@Slf4j
@Component
public class TubeAnalyzeServceImpl implements ITubeAnalyzeService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public ISearchTableService tableService;

    private List<String> gxIDList_LX = new ArrayList<String>();//存储所有管线->流向
    private List<String> gxIDList_SY = new ArrayList<String>();//存储所有管线->溯源
    private List<String> nodeIDList = new ArrayList<String>();//存储所有管点
    private List<String> tempNode = new ArrayList<String>();//存储每次查询中使用的管点
    private List<String> resultList = new ArrayList<String>();//存储所有点 阀门 ＃
    private List<String> node = new ArrayList<String>();//存储每次查询中获得的管点
    String pointTable = ""; //点表
    String lineTable = ""; //线表

    @Override
    public Map tubeAnalyze(Map map) throws IOException {
        String gxID= map.get("GXObjIdparm").toString();//查询管线USID
        lineTable = map.get("GXLyrIDparm").toString();//查询管线所在图层
        pointTable= map.get("GDLyrIDparm").toString();//查询管线对应管点图层
        String dm = lineTable.substring(0,lineTable.indexOf("_"));
        lineTable = tableService.searchLineTable(dm);
        pointTable = tableService.searchPointTable(dm);
        //String usID= request.getParameter("USIdparm");
        //----------------------------获取USID-------------------------------
        // gxIDList.add(gxID);//gxIDList，存储所有查询的管线，添加初始管线
        String sqlWhere = "select DM,QDDH,ZDDH,QDGC,ZDGC,QDMS,ZDMS,MSLX,CZ,GJ,DYZ,YL,LX,ZKS,ZYKS,DLTS,BHCZ,XX,GXFLDM,SZDL,QSDW,JSND,TCDW,TCRQ,SYZT,BZ,SNODID,ENODID,RKDATE,ISLOCK,US_ID from \"" + lineTable + "\" where US_ID='" + gxID + "'";
        //                         0   1   2    3    4    5    6    7    8  9 10  11 12  13  14   15   16  17   18    19   20   21   22   23   24  25   26     27     28     29     30
        List<Map<String, Object>> usidCursors = ToQueryFeatureCursor(sqlWhere);
        //int flag = 0;//查询次数多，时间长，游标报错
        if (usidCursors.size() != 0) {
            for (Map tempCursor : usidCursors) {
                tempNode.clear();//存储当次查询使用的管点
                node.clear();//存储当次查询获得的管点
                String snode = tempCursor.get("SNODID").toString();
                String enode = tempCursor.get("ENODID").toString();
                boolean isValve = nodeJudge(snode);//判断该点是否是阀门
                if (isValve) {
                    snode = enode;

                }
                nodeIDList.add(snode);  //加入阀门管点数组
                tempNode.add(snode);//存储当次查询使用的管点 初始输入管点，无论是不是阀门，都加入下轮查询

                //选择管线的一个端点，查找与之相连的所有管点和管线
                while (tempNode.size() != 0)//限制查询数量，共查询到20个不重复点结束
                {
                    REPEAT_gx();//按流向方向查找
                    REPEAT_gx_SY();//按溯源方向查找
//                    List<String> tempnode = new ArrayList<String>(tempNode);
                    tempNode.clear();//清空，下轮查询中使用
                    List<String> _node = new ArrayList<String>(node);

                    for (String item : _node) {
                        if (!nodeIDList.contains(item))//每次查询的管线经排查不会重复，但是管点可能重复(如 管线1-2，管线1-3中，管点1重复 )，因此排除重复管点
                        {
                            tempNode.add(item);//不重复的管点下次查询使用
                            nodeIDList.add(item);//不重复的管点添加到所有管点中
                        }

                    }
                    node.clear();//清空，下轮查询中存储查询到的管点
                }

            }
        }
        //REPEAT_gd();//所有管点中,查找阀门或阀门井
        StringBuilder result_node = new StringBuilder();//拼接字符串，存储结果
        if (resultList.size() > 0) {
            result_node.append("需要关闭的阀门编号:");
        }

        List list = disposeDataByType(dm,pointTable,resultList);

        JSONObject result = new JSONObject();
        result.put("result", list);
        //清空所有列表
        nodeIDList.clear();
        gxIDList_LX.clear();
        gxIDList_SY.clear();
        tempNode.clear();
        resultList.clear();
        node.clear();
        return result;
    }

    //判断是否是＃、阀门
    public boolean nodeJudge(String _toQuery) throws IOException
    {
        String sqlWhere = "select FSW,US_ID from \""+pointTable+"\" where NODEID='" + _toQuery + "'";
        List<Map<String, Object>> usidCursors = ToQueryFeatureCursor(sqlWhere);

        boolean flag = false;
        if (usidCursors.size() != 0)
        {
            for(Map tempCursor:usidCursors){

                String fsw = String.valueOf(tempCursor.get("FSW"));//查找附属物字段值
                String us_gd = tempCursor.get("US_ID").toString();
                if (fsw.contains("阀") ||fsw.contains("井") )
                {
                    if(!resultList.contains(us_gd)){
                        resultList.add(us_gd);
                    }
                    flag=true;
                }else{
                    flag=false;
                }
            }
        }
        return flag;
    }

    /**
     * @Title  对一组点按溯源方向查找
     * @Description
     * @param
     * @return
     * @author wangw
     *
     * @date 2020/7/13 0013 15:20
    */
    public void REPEAT_gx_SY() throws IOException
    {
        //String[] Result = tempNode.ToArray();
        // tempNode.clear();
        for (String item : tempNode)
        {
            GX_Query_SY(item);

        }
    }
    public void GX_Query_SY(String _toQuery) throws IOException
    {
        boolean isValve=nodeJudge(_toQuery);//判断该点是否是阀门
        if(!isValve){//如果不是阀门
            //String sqlWhere = "ENODID='" + _toQuery + "'";
            String sqlWhere = "select SNODID,US_ID from \""+lineTable+"\" where ENODID='" + _toQuery + "'";
            List<Map<String, Object>> usidCursors = ToQueryFeatureCursor(sqlWhere);
            if (usidCursors.size() != 0)
            {
                for(Map tempCursor:usidCursors){
                    String _tempLine = tempCursor.get("US_ID").toString();
                    if (!gxIDList_SY.contains(_tempLine))
                    {
                        node.add(tempCursor.get("SNODID").toString());//node中存储查询到的所有管点
                        gxIDList_SY.add(_tempLine);
                    }
                    //gxIDList.add(_feat.getValue(_feat.getTable().findField("US_ID")).toString());

                    // tempLine.add(_feat.getValue(_feat.getTable().findField("US_ID")).toString());//gxIDList中存储查询到的所有管线
                }
            }
        }
    }

    //对一组点按流向方向查找
    public void REPEAT_gx() throws IOException
    {
        for (String item : tempNode)
        {
            GX_Query_LX(item);//以已知点为SNODID(起点)，找ENODID(终点)
        }
    }
    public void GX_Query_LX(String _toQuery) throws IOException
    {
        boolean isValve=nodeJudge(_toQuery);//判断该点是否是阀门  是阀门则停止
        if(!isValve){//如果不是阀门则继续
            //String sqlWhere = "SNODID='" + _toQuery + "'";
    	        /*IFeatureCursor _featCursor = ToQueryFeatureCursor(sqlWhere, featClass_gx);//调用函数获得游标，查找要素集为管线要素集featClass_gx
    	        IFeature _feat = _featCursor.nextFeature();*/
            String sqlWhere = "select ENODID,US_ID from \""+lineTable+"\" where SNODID='" + _toQuery + "'";
            List<Map<String, Object>> usidCursors = ToQueryFeatureCursor(sqlWhere);
            if (usidCursors.size() != 0)
            {
                for(Map tempCursor:usidCursors){
                    String _tempLine = tempCursor.get("US_ID").toString();
                    if (!gxIDList_LX.contains(_tempLine))
                    {
                        node.add(tempCursor.get("ENODID").toString());//node中存储查询到的所有管点
                        gxIDList_LX.add(_tempLine);
                    }
                    //gxIDList.add(_feat.getValue(_feat.getTable().findField("US_ID")).toString());

                    // tempLine.add();//gxIDList中存储查询到的所有管线
                }
            }
        }
    }

    //获取满足查询条件 游标
    public List<Map<String, Object>> ToQueryFeatureCursor(String toQueryClause) {
        System.out.println("#############"+toQueryClause);
//        List<Object[]> result = lXAnalysisBaseDao.findBySql(toQueryClause);
        List<Map<String, Object>> result = jdbcTemplate.queryForList(toQueryClause);
        return result;
    }

    /**
     * @Title 根据管线类型处理数据
     * @Description
     * @return
     * @author wangw
     * @date 2020/7/14 0014 11:34
     */
    public List disposeDataByType(String dm,String tableName,List userIdList){
        List list = new ArrayList();
        for (int i = 0; i < userIdList.size(); i++) {
            String sql = "select * from \""+tableName+"\" where US_ID ='"+userIdList.get(i).toString()+"'";
            Double [] point = new Double[2];
                POINT cpoint = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<POINT>(POINT.class));
                list.add(cpoint);
                point[0] = Double.valueOf(cpoint.getNODEID().split("-")[1]);
                point[1] = Double.valueOf(cpoint.getNODEID().split("-")[0]);
                cpoint.setPoint(point);
        }
        return list;
    }
}
